package com.controller;

import com.bean.Msg;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import com.utils.CommonUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 验证码的controller
 * @author WxrStart
 * @create 2022-05-18 15:59
 */



@Controller
public class CaptchaController {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private DefaultKaptcha defaultKaptcha;


    /**
     * 设置每个UserKey过期时间为10分钟，避免一直用户一直输入不正确，或者是一直挂到页面不走了浪费Redis内存空间
     */
    private static final long CAPTCHA_CODE_EXPIRED = 10*60 * 1000  ;

    /**
     * 获取图形验证码
     * @param request
     * @param response
     * @return void
     **/
    @GetMapping("/captcha")
    @ResponseBody
    public Msg getCaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
//        String captchaProducerText = captchaProducer.createText();

//        BufferedImage bufferedImage = captchaProducer.createImage(captchaProducerText);
//        ServletOutputStream outputStream = null;
//
//        try {
//            outputStream = response.getOutputStream();
//            ImageIO.write(bufferedImage, "jpg", outputStream);
//            String imgString = "data:image/gif;base64," + Base64.encode(outputStream.to());
//            outputStream.flush();
//            outputStream.close();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }


        // 生成验证码
        String code = defaultKaptcha.createText();
        //存入Redis
        redisTemplate.opsForValue().set(getCaptchaKey(request),code,CAPTCHA_CODE_EXPIRED, TimeUnit.MILLISECONDS);
        // 生成图片验证码
        BufferedImage image = defaultKaptcha.createImage(code);
        // 转为Base64
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        ImageIO.write(image, "png", stream);
        String imgString = "data:image/gif;base64," + Base64.encode(stream.toByteArray());
        stream.flush();
        stream.close();
        // 将数据存入并将其返回
        return Msg.success().add("result",imgString);

    }

    /**
     * 给Redis拼接userkey
     * @param request
     * @return java.lang.String
     **/
    private String getCaptchaKey(HttpServletRequest request) {

        String ip = CommonUtil.getIpAddr(request);
        String userAgent = request.getHeader("User-Agent");
        String userkey = "user:captcha:" + CommonUtil.MD5(ip + userAgent);
        return userkey;
    }


    /**
     * 判断验证码是否输入正确
     * 输入正确就从Redis中删掉
     * @param captcha
     * @param request
     **/
    @GetMapping("/send_code")
    @ResponseBody
    public Msg sendRegisterCode(@RequestParam(value = "captcha",required = true)String captcha, HttpServletRequest request){

        String key = getCaptchaKey(request);
        String cacheCaptcha = redisTemplate.opsForValue().get(key);
        if (captcha != null && cacheCaptcha != null && cacheCaptcha.equalsIgnoreCase(captcha)) {
            redisTemplate.delete(key);
            return Msg.success().add("result","验证成功");
        }else {
            return Msg.fail().add("result","验证码错误，请重新输入");
        }
    }
}

